<?php
namespace hangpu8\hpcms\service;

use hangpu8\hpcms\model\Admin as ModelAdmin;
use think\Exception;

class Admin
{
    private $db;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->db = new ModelAdmin;
    }

    /**
     * 获取列表数据
     *
     * @param array $where
     * @param string $order
     * @param string $field
     * @param integer $limit
     * @return array
     */
    public function getlist($where = [],$order = 'id desc',$field = '*',$limit = 300) : array
    {
        $status = ['锁定','正常'];
        $map = [];
        if ($where)
        {
            $map = $where;
        }
        $list = ModelAdmin::with('profile')
        ->where($map)
        ->order($order)
        ->field($field)
        ->paginate($limit)
        ->each(function($item)use($status){
            if (isset($item['status']))
            {
                $item['status_text'] = $status[$item['status']];
            }
            if (isset($item['profile']['title']))
            {
                $item['admin_role'] = $item['profile']['title'];
            }
            return $item;
        })
        ->toArray();
        return $list;
    }
    
    /**
     * 创建数据
     *
     * @param array $post
     * @return bool
     */
    public function create(array $post) : bool
    {
        if ($this->db->save($post))
        {
            return true;
        }else{
            throw new Exception("添加数据失败",404);
        }
    }
    
    /**
     * 修改数据
     *
     * @param array $post
     * @param array $map
     * @return boolean
     */
    public function saveUpdate(array $post,array $map) : bool
    {
        try {
            return $this->db->where($map)->save($post);
        } catch (\Throwable $e) {
            throw new Exception($e->getMessage(),404);
        }
    }

    /**
     * 删除数据
     *
     * @param [type] $id
     * @return void
     */
    public function del($id)
    {
        try {
            $adminRole = ModelAdmin::where(['id'=> $id])->find();
            // 删除
            return $adminRole->delete();
        } catch (\Throwable $e) {
            throw new Exception($e->getMessage(),404);
        }
    }

    /**
     * 获取表单数据
     *
     * @param array $where
     * @return array
     */
    public function getForm(array $where) : array
    {
        $data = $this->db->where($where)->find();
        if ($data)
        {
            $data = $data->toArray();
            $data['password'] = '';
        }
        return $data;
    }
}